<template>
    <div>
        <queryView v-model="queryParams" @query="getListData(1)" @create="handleCreate" />
        <el-card shadow="hover">
            <el-table v-loading="tableDataLoading" :data="tableData" table-layout="auto">
                <el-table-column align="center" type="index" label="#" min-width="50" />
                <el-table-column align="center" prop="nickname" label="昵称" />
                <el-table-column align="center" label="头像" width="180">
                    <template #default="scope">
                        <el-image
                            :preview-src-list="[scope.row.avatar]"
                            style="height: 60px; width: 60px; border-radius: 50%"
                            :src="scope.row.avatar"
                            :lazy="true"
                            fit="cover"
                            preview-teleported />
                    </template>
                </el-table-column>
                <el-table-column align="center" prop="username" label="用户名" />
                <el-table-column align="center" label="所属角色">
                    <template #default="scope">
                        <el-tag type="primary">
                            <span v-if="scope.row.role_names.length == 0">无</span>
                            <span v-else>{{ scope.row.role_names.toString() }}</span>
                        </el-tag>
                    </template>
                </el-table-column>
                <el-table-column align="center" prop="phone" label="手机号"></el-table-column>
                <el-table-column align="center" prop="status" label="状态">
                    <template #default="scope">
                        <el-switch
                            v-model="scope.row.status"
                            @change="handleSwitchChange($event, scope.row.id)"
                            :active-value="1"
                            :inactive-value="2" />
                    </template>
                </el-table-column>
                <el-table-column align="center" prop="register_ip" label="注册IP" />
                <el-table-column align="center" prop="created_at" label="注册时间" />
                <el-table-column align="center" fixed="right" label="操作" width="120">
                    <template #default="scope">
                        <el-button link type="primary" size="small" @click="handleEdit(scope.row)"> 编辑 </el-button>
                        <el-button link type="danger" size="small" @click="handleDelete(scope.row.id)">删除</el-button>
                    </template>
                </el-table-column>
            </el-table>
            <div style="margin-top: 20px">
                <el-pagination
                    v-model:current-page="page"
                    v-model:page-size="pageSize"
                    @update:current-page="getListData()"
                    @update:page-size="getListData()"
                    layout="total,sizes,prev, pager, next,jumper"
                    size="small"
                    background
                    :page-sizes="[20, 50, 100, 200, 500]"
                    :total="total" />
            </div>
            <!-- 弹窗 -->
            <el-dialog
                v-model="dialogFormVisible"
                :title="formIsEdit ? '编辑' : '新增'"
                width="600px"
                destroy-on-close
                :close-on-click-modal="false">
                <el-form ref="formRef" :model="form" :rules="rules" label-width="80px">
                    <el-form-item label="用户名" prop="username" style="width: 300px">
                        <el-input v-model="form.username" :disabled="formIsEdit" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="密码" prop="password" style="width: 300px">
                        <el-input v-model="form.password" type="password" show-password autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="昵称" prop="nickname" style="width: 300px">
                        <el-input v-model="form.nickname" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="头像" prop="avatar">
                        <ymiUpload v-model="form.avatar" name="image" :is-list="false" :width="90" :height="90" />
                    </el-form-item>
                    <el-form-item label="手机号" prop="phone" style="width: 300px">
                        <el-input v-model="form.phone" autocomplete="off" />
                    </el-form-item>
                    <el-form-item label="角色" prop="role_ids" style="width: 300px">
                        <el-select v-model="form.role_ids" multiple placeholder="请选择角色" clearable>
                            <template v-for="role in options.roles" :key="role.id">
                                <el-option :value="role.id" :label="role.cn_name" />
                            </template>
                        </el-select>
                    </el-form-item>
                    <el-form-item label="状态" prop="status">
                        <el-switch v-model="form.status" :active-value="1" :inactive-value="2" />
                    </el-form-item>
                </el-form>
                <template #footer>
                    <div class="dialog-footer">
                        <el-button @click="dialogFormVisible = false">取 消</el-button>
                        <el-button type="primary" @click="handleSubmit(formRef)">确 定</el-button>
                    </div>
                </template>
            </el-dialog>
        </el-card>
    </div>
</template>

<script setup lang="ts">
    // import { apiAdmin } from '@/api/test'
    import { apiAdmin, getAdminOptions } from '@/api/restful'
    import type { ComponentSize, FormInstance, FormRules } from 'element-plus'
    import type { Admin } from '@/types/global'
    import ymiUpload from '@/components/ymi/ymiUpload.vue'
    import queryView from './queryView.vue'
    const total = ref(0)
    const page = ref(1)
    const pageSize = ref(20)
    const tableDataLoading = ref(true)
    const tableData = ref<Admin[]>([])
    const options = ref<any>({ roles: [] })
    const queryParams = ref({})

    const dialogFormVisible = ref(false)
    const formRef = ref<FormInstance>()
    const formIsEdit = ref(false)
    const form = ref<Admin>({
        id: '',
        status: 1,
        nickname: '',
        avatar: '',
        phone: '#',
        role_ids: []
    })
    const rules = reactive<FormRules<Admin>>({
        nickname: [{ required: true, message: '请输入昵称', trigger: 'blur' }],
        username: [{ required: true, message: '请输入用户名', trigger: 'blur' }],
        avatar: [{ required: true, message: '请上传头像', trigger: 'blur' }]
    })
    onMounted(() => {
        getListData()
        getAdminOptions({}).then((res) => {
            console.log('获取管理员列表', res)
            options.value = res.data
        })
    })

    /**
     * 获取列表数据
     */
    const getListData = (nowPage?: number) => {
        tableDataLoading.value = true
        if (nowPage) page.value = nowPage
        const paramsData = {
            ...{ page: page.value, pageSize: pageSize.value },
            ...queryParams.value
        }
        apiAdmin(paramsData, 'GET')
            .then((res) => {
                console.log(res.data?.data)
                tableDataLoading.value = false
                tableData.value = res.data?.data
                total.value = res.data?.total
            })
            .catch(() => {
                tableDataLoading.value = false
            })
    }
    const handleCreate = () => {
        formIsEdit.value = false
        form.value = {} as Admin
        dialogFormVisible.value = true
    }

    /**
     * 处理表单提交
     * @param formEl
     */
    const handleSubmit = async (formEl: FormInstance | undefined) => {
        if (!formEl) return
        await formEl.validate((valid, fields) => {
            if (!valid) return
            dialogFormVisible.value = false
            if (formIsEdit.value) {
                updateRequest(form.value, '保存成功')
                return
            }
            apiAdmin(form.value, 'POST').then((res) => {
                ElMessage({
                    type: 'success',
                    message: '新增成功'
                })
                getListData()
            })
        })
    }

    /**
     * 删除
     */
    const handleDelete = (id: number) => {
        ElMessageBox.confirm('确认删除吗？', '提示', {
            confirmButtonText: '确定',
            cancelButtonText: '取消',
            type: 'warning'
        }).then(() => {
            apiAdmin({ id }, 'DELETE').then((res) => {
                ElMessage({
                    type: 'success',
                    message: '删除成功'
                })
                getListData()
                console.log(res)
            })
        })
    }
    /**
     * 编辑
     */
    const handleEdit = (row: Admin) => {
        console.log(row)
        form.value = { ...row }
        formIsEdit.value = true
        dialogFormVisible.value = true
    }
    /**
     * 更新请求
     * @param params
     * @param msg
     */
    const updateRequest = (params: any, msg = '更新成功') => {
        apiAdmin(params, 'PUT').then((res) => {
            ElMessage({
                type: 'success',
                message: msg
            })
            getListData()
        })
    }
    /**
     * 处理表格数据switch事件
     * @param value
     * @param id
     */
    const handleSwitchChange = (value: any, id: number) => {
        updateRequest({ id, status: value }, '更新成功')
    }
</script>

<style></style>
